
from django import forms
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
from link import models
import urllib
import logging

def my_url_encode(text):
	return urllib.urlencode( { 'q': text.encode('utf-8') } )[2:]

def list_links(request):
	user = users.get_current_user()
	logout_url = users.create_logout_url("/")
	query = db.Query(models.MyLink).filter('user =', user)
	query.order('link')
	links = query.fetch(100)
	if links:
		return render_to_response('link/list.html', { 'logout_url': logout_url, 'links': links })
	else:
		return render_to_response('link/list.html', { 'logout_url': logout_url, 'links': [] })


class EditLinkForm(forms.Form):
	link = forms.CharField(label='link', help_text='link keyword of your choice')
	path = forms.URLField(label='url', help_text='url of the destination web site. e.g. http://www.google.com/', required=False)
	query_path = forms.URLField(label='query url', help_text='(optional) url used for direct query. e.g. http://www.google.com/q=', required=False)
	comment = forms.CharField(label='comment', help_text='(optional) human friendly name of the site. e.g. Google', required=False)


def delete_link(request, link=None):
	user = users.get_current_user()
	if user and link:
		models.MyLink.delete( models.get_link( user, link ) )
	return HttpResponseRedirect('/')
	
def edit_link_form(request, link):
	user = users.get_current_user()
	if request.method == 'POST':
		form = EditLinkForm(request.POST)
		# the form was submitted
		if form.is_valid():
			# fetch the existing link and update it from the form
			entry = models.get_link( user, form.cleaned_data['link'] )
			entry.link = form.cleaned_data['link']
			entry.path = form.cleaned_data['path']
			if entry.path:
				entry.query_path = form.cleaned_data['query_path']
				entry.comment = form.cleaned_data['comment']
				entry.user = user
				entry.put()
			else:
				# delete the entry if path is empty
				models.MyLink.delete( entry )
			return HttpResponseRedirect('/')
		#else fall through to redisplay the form with error messages
	else:
		# the user wants to see the form
		if link:
			# show the form to edit an existing link
			entry = models.get_link( user, link )
			data = { 'link': link, 'path': entry.path, 'query_path':entry.query_path, 'comment': entry.comment }
			form = EditLinkForm( data )
		else:
			form = EditLinkForm()
	return render_to_response('link/edit.html', {'form': form})

def edit_link_word(request, link):
	return HttpResponseRedirect( '/edit/' + my_url_encode( link ) )
	
def dispatch_single_word(request, word):
	user = users.get_current_user()
	entry = db.get( models.get_link_key( user, word ) )
	if entry:
		return HttpResponseRedirect(entry.path)
	else:
		return HttpResponseRedirect( 'http://www.google.com/search?q=' + my_url_encode(word) )

def dispatch_multiple_words(request, first_word, the_rest):
	user = users.get_current_user()
	entry = db.get( models.get_link_key( user, first_word ) )
	if entry and entry.query_path:
		return HttpResponseRedirect( entry.query_path + my_url_encode(the_rest) )
	return HttpResponseRedirect( 'http://www.google.com/search?q=' + my_url_encode(request.path[1:]) )

